import { useState } from 'react';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';
import type { SupportedChain } from '@/contexts/MultiChainWalletContext';

interface ChainConfig {
  id: SupportedChain;
  name: string;
  icon: string;
  color: string;
  description: string;
}

const SUPPORTED_CHAINS: ChainConfig[] = [
  {
    id: 'solana',
    name: 'Solana',
    icon: '◎',
    color: 'text-purple-500',
    description: 'Fast, decentralized blockchain'
  },
  {
    id: 'bsc',
    name: 'BSC',
    icon: '🔶',
    color: 'text-yellow-500',
    description: 'Binance Smart Chain'
  },
  {
    id: 'xlayer',
    name: 'XLayer',
    icon: '🔷',
    color: 'text-blue-500',
    description: 'OKX L2 Network'
  }
];

export function MultiChainWalletConnect() {
  const [isConnecting, setIsConnecting] = useState(false);
  const [selectedChain, setSelectedChain] = useState<SupportedChain | null>(null);
  
  const {
    connected,
    connecting,
    address,
    chain,
    balance,
    connectWallet,
    disconnectWallet,
    switchChain,
    isSupported
  } = useMultiChainWallet();

  const handleConnect = async (chainId: SupportedChain) => {
    if (!isSupported(chainId)) {
      alert(`${chainId} 钱包未安装或不支持`);
      return;
    }

    setIsConnecting(true);
    setSelectedChain(chainId);
    
    try {
      await connectWallet(chainId);
    } catch (error) {
      console.error('连接钱包失败:', error);
      alert(`连接 ${chainId} 钱包失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsConnecting(false);
      setSelectedChain(null);
    }
  };

  const handleSwitchChain = async (chainId: SupportedChain) => {
    if (!isSupported(chainId)) {
      alert(`${chainId} 钱包未安装或不支持`);
      return;
    }

    try {
      await switchChain(chainId);
    } catch (error) {
      console.error('切换链失败:', error);
      alert(`切换到 ${chainId} 失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  const handleDisconnect = async () => {
    try {
      await disconnectWallet();
    } catch (error) {
      console.error('断开连接失败:', error);
    }
  };

  const formatAddress = (addr: string): string => {
    return `${addr.slice(0, 6)}...${addr.slice(-4)}`;
  };

  if (connected) {
    return (
      <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-bold text-white">钱包已连接</h3>
          <button
            onClick={handleDisconnect}
            className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-sm rounded"
          >
            断开连接
          </button>
        </div>
        
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <span className="text-gray-400">链:</span>
            <span className={`font-medium ${SUPPORTED_CHAINS.find(c => c.id === chain)?.color}`}>
              {SUPPORTED_CHAINS.find(c => c.id === chain)?.icon} {SUPPORTED_CHAINS.find(c => c.id === chain)?.name}
            </span>
          </div>
          
          <div className="flex items-center gap-2">
            <span className="text-gray-400">地址:</span>
            <span className="text-white font-mono text-sm">{address ? formatAddress(address) : '未知'}</span>
          </div>
          
          {balance && (
            <div className="flex items-center gap-2">
              <span className="text-gray-400">余额:</span>
              <span className="text-white">{balance}</span>
            </div>
          )}
        </div>

        <div className="mt-4">
          <h4 className="text-sm text-gray-400 mb-2">切换到其他链:</h4>
          <div className="flex gap-2">
            {SUPPORTED_CHAINS.filter(c => c.id !== chain).map((chainConfig) => (
              <button
                key={chainConfig.id}
                onClick={() => handleSwitchChain(chainConfig.id)}
                disabled={!isSupported(chainConfig.id)}
                className={`px-3 py-1 text-sm rounded border ${
                  isSupported(chainConfig.id)
                    ? 'border-gray-600 hover:border-gray-500 text-white hover:bg-gray-800'
                    : 'border-gray-700 text-gray-500 cursor-not-allowed'
                }`}
              >
                {chainConfig.icon} {chainConfig.name}
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
      <h3 className="text-lg font-bold text-white mb-4">连接钱包</h3>
      
      <div className="space-y-3">
        {SUPPORTED_CHAINS.map((chainConfig) => {
          const isChainSupported = isSupported(chainConfig.id);
          const isChainConnecting = isConnecting && selectedChain === chainConfig.id;
          
          return (
            <button
              key={chainConfig.id}
              onClick={() => handleConnect(chainConfig.id)}
              disabled={!isChainSupported || connecting || isConnecting}
              className={`w-full p-3 rounded-lg border transition-colors ${
                isChainSupported
                  ? 'border-gray-600 hover:border-gray-500 hover:bg-gray-800 text-white'
                  : 'border-gray-700 bg-gray-800 text-gray-500 cursor-not-allowed'
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <span className={`text-xl ${chainConfig.color}`}>
                    {chainConfig.icon}
                  </span>
                  <div className="text-left">
                    <div className="font-medium">{chainConfig.name}</div>
                    <div className="text-sm text-gray-400">{chainConfig.description}</div>
                  </div>
                </div>
                
                <div className="text-right">
                  {isChainConnecting ? (
                    <div className="text-sm text-blue-400">连接中...</div>
                  ) : !isChainSupported ? (
                    <div className="text-sm text-gray-500">未安装</div>
                  ) : (
                    <div className="text-sm text-gray-400">点击连接</div>
                  )}
                </div>
              </div>
            </button>
          );
        })}
      </div>
      
      <div className="mt-4 p-3 bg-gray-800 rounded-lg">
        <div className="text-sm text-gray-400">
          <div className="font-medium mb-1">钱包安装说明:</div>
          <ul className="space-y-1 text-xs">
            <li>• Solana: 安装 Phantom 或 Solflare 钱包</li>
            <li>• BSC/XLayer: 安装 MetaMask 钱包</li>
            <li>• 确保钱包扩展已启用并解锁</li>
          </ul>
        </div>
      </div>
    </div>
  );
}
